package com.firefightingiot_data.data.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.firefightingiot_data.data.common.base.BaseService;
import com.firefightingiot_data.data.common.utils.Dict;
import com.firefightingiot_data.data.common.utils.appkit.FirefightingiotKit;
import com.firefightingiot_data.data.support.model.RespEntity;
import com.firefightingiot_data.data.support.mybatisplus.QueryWrapper;
import com.firefightingiot_data.data.support.utils.DayUtil;
import com.firefightingiot_data.data.support.utils.MyLogger;
import com.firefightingiot_data.data.web.mapper.DeviceBusinessMapper;
import com.firefightingiot_data.data.web.mapper.DeviceNormalItemsMapper;
import com.firefightingiot_data.data.web.mapper.DeviceNormalLogMapper;
import com.firefightingiot_data.data.web.mapper.ItemLogFieldMappingMapper;
import com.firefightingiot_data.data.web.model.*;
import com.taosdata.jdbc.TSDBDriver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.*;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @Author: YangYu
 * @ClassName: NormalDataLogService
 * @Date: Created in 15:11 2022/4/21
 * @Description: 正常数据
 */
@Service
@Slf4j
public class NormalDataLogService extends BaseService {

    @Resource
    public MyLogger logger;
    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;
    @Resource
    private DeviceNormalItemsMapper deviceNormalItemsMapper;
    @Resource
    ItemLogFieldMappingMapper itemLogFieldMappingMapper;
    @Resource
    private DeviceNormalLogMapper deviceNormalLogMapper;

    /**
     * @Author YangYu
     * @Description 正常数据添加
     * @Date Created in 15:28 2022/4/21
     * @Param [jsonParam]
     */

    public RespEntity normalDataLogAdd(JSONObject jsonParam) {
        logger.info("-------------------------------------normalDataLogAdd------------------------" + jsonParam.toString());
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusinessList.isEmpty()) return RespEntity.fail("设备编号不存在");
        DeviceBusiness deviceBusiness = deviceBusinessList.get(0);
        //更新最新时间的和设备的状态为在线
        DeviceBusiness deviceBusinessN = new DeviceBusiness();
        deviceBusinessN.setId(deviceBusiness.getId());
        deviceBusinessN.setNormalUpdateTime(DateUtil.now());
        if (!deviceBusiness.getCurrentstate().equals("4")){
            if (!deviceBusiness.getCurrentstate().equals("1")) {
                deviceBusinessN.setCurrentstate("1");
                //deviceBusinessMapper.updateById(deviceBusinessN);
            }
        }
        jsonParam.put("deviceClassify", deviceBusiness.get("device_classify"));
        String senddate = "";
        String sendtime = "";
        String time = jsonParam.getStr("time");
        if (StrUtil.isBlank(time)) return RespEntity.fail("time为空");
        String times[] = time.split(" ");
        senddate = times[0];
        sendtime = times[1];
        JSONArray jSONArray = jsonParam.getJSONArray("paraminfo");
        Dict fireMap = new Dict();
        //获取所有的二级正常数据项
        List<DeviceNormalItems> deviceNormalItemsList = deviceNormalItemsMapper.selectList(new QueryWrapper<DeviceNormalItems>().eq("level", 2));
        List<String> nameList = new ArrayList<>();
        for (DeviceNormalItems item : deviceNormalItemsList) {
            nameList.add(item.getName());
        }
        //获取最终插入表字段名和值的映射关系
        JSONObject fieldValueMap = getElectricFireItemMap(jSONArray, nameList);
        //存放正常数据项之外的数据
        fieldValueMap.put("id", UUID.randomUUID().toString());
        fieldValueMap.put("device_id", deviceBusiness.get("id"));
        fieldValueMap.put("number", deviceBusiness.get("number"));
        fieldValueMap.put("senddate", DateUtil.parseDate(senddate));
        fieldValueMap.put("sendtime", sendtime);
        fieldValueMap.put("business_id", deviceBusiness.get("business_id"));
        fieldValueMap.put("business_name", deviceBusiness.get("business_name"));
        //保存最终数据到正常数据日志表
        if (jsonParam.getStr("deviceClassify").equals("1")) {//电气火灾
            fieldValueMap.put("table", "device_normal_log_electric_fire_" + DayUtil.getToday());
            deviceNormalLogMapper.inserDeviceNormalLogElectricFire(fieldValueMap);
            //在总表存储一份
            fieldValueMap.put("table", "device_normal_log_all");
            deviceNormalLogMapper.inserDeviceNormalLogElectricFire(fieldValueMap);
            //涛思

        } else if (jsonParam.getStr("deviceClassify").equals("2")) {//消防用水
            fieldValueMap.put("table", "device_normal_log_fire_water_" + DayUtil.getToday());
            deviceNormalLogMapper.inserDeviceNormalLogFireWater(fieldValueMap);
            //在总表存储一份
            fieldValueMap.put("table", "device_normal_log_all");
            deviceNormalLogMapper.inserDeviceNormalLogFireWater(fieldValueMap);
        } else if (jsonParam.getStr("deviceClassify").equals("3")) {//烟感
            fieldValueMap.put("table", "device_normal_log_smoke_" + DayUtil.getToday());
            deviceNormalLogMapper.inserDeviceNormalLogSmoke(fieldValueMap);
            //在总表存储一份
            fieldValueMap.put("table", "device_normal_log_all");
            deviceNormalLogMapper.inserDeviceNormalLogSmoke(fieldValueMap);
        } else if (jsonParam.getStr("deviceClassify").equals("4")) {//可燃气体
            fieldValueMap.put("table", "device_normal_log_gas_" + DayUtil.getToday());
            deviceNormalLogMapper.inserDeviceNormalLogGas(fieldValueMap);
            //在总表存储一份
            fieldValueMap.put("table", "device_normal_log_all");
            deviceNormalLogMapper.inserDeviceNormalLogGas(fieldValueMap);
        }else if (jsonParam.getStr("deviceClassify").equals("7")) {//灭火器
            fieldValueMap.put("table", "device_normal_log_extinguisher_" + DayUtil.getToday());
            deviceNormalLogMapper.inserDeviceNormalLogExtinguisher(fieldValueMap);
            //在总表存储一份
            fieldValueMap.put("table", "device_normal_log_all");
            deviceNormalLogMapper.inserDeviceNormalLogExtinguisher(fieldValueMap);
        }else if (jsonParam.getStr("deviceClassify").equals("10")) {//水泵
            fieldValueMap.put("table", "device_normal_log_water_pump_" + DayUtil.getToday());
            deviceNormalLogMapper.inserDeviceNormalLogWaterPump(fieldValueMap);
            //在总表存储一份
            fieldValueMap.put("table", "device_normal_log_all");
            deviceNormalLogMapper.inserDeviceNormalLogWaterPump(fieldValueMap);
        }else if (jsonParam.getStr("deviceClassify").equals("21")) {//温湿度
            fieldValueMap.put("table", "device_normal_log_temperature_humidity_" + DayUtil.getToday());
            deviceNormalLogMapper.inserDeviceNormalLogTemperatureHumidity(fieldValueMap);
            //在总表存储一份
            fieldValueMap.put("table", "device_normal_log_all");
            deviceNormalLogMapper.inserDeviceNormalLogTemperatureHumidity(fieldValueMap);
        }else if (jsonParam.getStr("deviceClassify").equals("22")) {//充电桩安全
            fieldValueMap.put("table", "device_normal_log_charging_station_" + DayUtil.getToday());
            deviceNormalLogMapper.inserDeviceNormalLogChargingStation(fieldValueMap);
            //在总表存储一份
            fieldValueMap.put("table", "device_normal_log_all");
            deviceNormalLogMapper.inserDeviceNormalLogChargingStation(fieldValueMap);
        }
        //数据订阅
        jsonParam.put("businessId",deviceBusiness.get("business_id"));
        jsonParam.put("type","normal");
        //存到涛思数据库
        //addTaosNormalData(fieldValueMap,senddate,sendtime,jsonParam);
        return RespEntity.success();
    }

    //组装小项名称和实时数据值的映射
    public JSONObject getElectricFireItemMap(JSONArray jSONArray, List<String> nameList) {
        JSONObject jSONObject = new JSONObject();//组装最终数据
        Map<String, String> map = getFieldItemMap();//获取正常二级数据项和正常数据日志字段的映射
        for (int i = 0; i < jSONArray.size(); i++) {
            JSONObject item = (JSONObject) jSONArray.get(i);
            if (!nameList.contains(item.getStr("name"))) continue;//如果数据库找不大，直接舍去
            if (item.getStr("value")==null||StrUtil.isBlank(item.getStr("value"))) continue;
            //保留两位小数
            DecimalFormat df = new DecimalFormat("#.##");
            try {
                jSONObject.put(map.get(item.getStr("name")),df.format(item.getDouble("value")));//组装最终存表的字段名和值的映射
            }catch (Exception e){
                continue;
            }
        }
        return jSONObject;
    }
    //获取正常二级数据项和正常数据日志字段的映射
    public Map<String, String> getFieldItemMap() {
        Map<String, String> map = new HashMap<>();//组装数据
        //获取获取正常二级数据项和正常数据日志字段的映射关系列表
        List<ItemLogFieldMapping> list = itemLogFieldMappingMapper.selectList(new QueryWrapper<>());
        for (ItemLogFieldMapping mapping : list) {
            map.put(mapping.getStr("item_name"), mapping.getStr("log_value_name"));
        }
        return map;
    }
    /**
     * @Author YangYu
     * @Description 涛思数据库正常数据添加
     * @Date Created in 14:19 2023/6/1
     * @Param [deviceNormalLog, sendDate, sendTime, jsonParam]
     */

    public void addTaosNormalData(JSONObject deviceNormalLog,String sendDate, String sendTime ,JSONObject jsonParam){

        //cmds命令必须分开写，不能有空格
        //极智
        //String[] cmds={"curl","-H","Authorization:Basic cm9vdDpqaXpoaUAxMjMu","-d","insert into device_normal_log_all_child values(now,'abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc')","58.220.33.127:6041/rest/sql/device"};
        //互联通
        String[] cmds={"curl","-H","Authorization:Basic cm9vdDpqaXpoaUAxMjMu","-d","insert into device_normal_log_all_child values(now,'abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc','abc')","36.138.49.84:6041/rest/sql/device"};
        cmds[4] = "insert into device_normal_log_all_child values(now,'"+deviceNormalLog.get("id")+"','"+deviceNormalLog.get("device_id")+"','"+deviceNormalLog.get("number")+"','"+sendDate+"','"+sendTime+"','"+deviceNormalLog.get("business_id")+"','"+deviceNormalLog.get("business_name")+"','"+deviceNormalLog.get("a_voltage_value")+"','"+deviceNormalLog.get("b_voltage_value")+"','"+deviceNormalLog.get("c_voltage_value")+"','"+deviceNormalLog.get("a_electric_value")+"','"+deviceNormalLog.get("b_electric_value")+"','"+deviceNormalLog.get("c_electric_value")+"','"+deviceNormalLog.get("dual_electric_value")+"','"+deviceNormalLog.get("a_temp_value")+"','"+deviceNormalLog.get("b_temp_value")+"','"+deviceNormalLog.get("c_temp_value")+"','"+deviceNormalLog.get("n_temp_value")+"','"+deviceNormalLog.get("active_electric")+"','"+deviceNormalLog.get("a_voltage_angle")+"','"+deviceNormalLog.get("b_voltage_angle")+"','"+deviceNormalLog.get("c_voltage_angle")+"','"+deviceNormalLog.get("a_electric_angle")+"','"+deviceNormalLog.get("b_electric_angle")+"','"+deviceNormalLog.get("c_electric_angle")+"','"+deviceNormalLog.get("a_active_power")+"','"+deviceNormalLog.get("b_active_power")+"','"+deviceNormalLog.get("c_active_power")+"','"+deviceNormalLog.get("a_reactive_power")+"','"+deviceNormalLog.get("b_reactive_power")+"','"+deviceNormalLog.get("c_reactive_power")+"','"+deviceNormalLog.get("a_apparent_power")+"','"+deviceNormalLog.get("b_apparent_power")+"','"+deviceNormalLog.get("c_apparent_power")+"','"+deviceNormalLog.get("a_power_factor")+"','"+deviceNormalLog.get("b_power_factor")+"','"+deviceNormalLog.get("c_power_factor")+"','"+deviceNormalLog.get("all_active_power")+"','"+deviceNormalLog.get("all_reactive_power")+"','"+deviceNormalLog.get("all_apparent_power")+"','"+deviceNormalLog.get("all_power_factor")+"','"+deviceNormalLog.get("a_voltage_harmonic")+"','"+deviceNormalLog.get("b_voltage_harmonic")+"','"+deviceNormalLog.get("c_voltage_harmonic")+"','"+deviceNormalLog.get("a_electric_harmonic")+"','"+deviceNormalLog.get("b_electric_harmonic")+"','"+deviceNormalLog.get("c_electric_harmonic")+"','"+deviceNormalLog.get("water_pressure")+"','"+deviceNormalLog.get("water_level")+"','"+deviceNormalLog.get("methane")+"','"+deviceNormalLog.get("extinguisherpressure")+"','"+deviceNormalLog.get("smoke_concentration")+"','"+deviceNormalLog.get("temperature")+"','"+deviceNormalLog.get("electric_leakage")+"','"+deviceNormalLog.get("battery")+"','"+deviceNormalLog.get("signal")+"','1','1','1','1','1','"+jsonParam.getStr("time")+"')";
        try {
            System.out.println(execCurl(cmds));
        }catch (Exception e){
            System.out.println(e.toString());
        }

    }

    /**
     * @Author YangYu
     * @Description cmd命令执行
     * @Date Created in 17:23 2023/5/31
     * @Param [cmds]
     */

    public static String execCurl(String[] cmds) {

        ProcessBuilder process = new ProcessBuilder(cmds);

        Process p;

        try {

            p = process.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

            StringBuilder builder = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {

                builder.append(line);

                builder.append(System.getProperty("line.separator"));

            }

            return builder.toString();

        } catch (IOException e) {

            System.out.print("error");

            e.printStackTrace();

        }

        return null;

    }
    public static Connection getConn() throws Exception{
        Class.forName("com.taosdata.jdbc.TSDBDriver");
        String jdbcUrl = "jdbc:TAOS://58.220.33.127:6041/device?user=root&password=jizhi@123.";
        Properties connProps = new Properties();
        connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
        connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
        connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
        connProps.setProperty("debugFlag", "135");
        connProps.setProperty("maxSQLLength", "1048576");
        Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
        return conn;
    }

    public static Connection getRestConn() throws Exception{
        Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
        //极智
        //String jdbcUrl = "jdbc:TAOS-RS://58.220.33.127:6041/device?user=root&password=jizhi@123.";
        //互联通
        //String jdbcUrl = "jdbc:TAOS-RS://36.138.49.84:6041/device?user=root&password=jizhi@123.";
        //智慧云
        String jdbcUrl = "jdbc:TAOS-RS://121.89.218.62:6041/device?user=root&password=jizhi@123.";
        Properties connProps = new Properties();
        connProps.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true");
        Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
        return conn;
    }

    public static void main(String[] args) throws Exception {
        Connection conn = getRestConn();
        Statement stmt = conn.createStatement();
        // query data
        ResultSet resultSet = stmt.executeQuery("select * from device_normal_log_electric_fire where number = '863716041049286'");
        List<DeviceAlarmLog> list = new ArrayList<>();
        while(resultSet.next()){
            DeviceAlarmLog deviceAlarmLog = new DeviceAlarmLog();
            deviceAlarmLog.setId(resultSet.getString("id"));
            deviceAlarmLog.setDeviceId(resultSet.getString("device_id"));
            list.add(deviceAlarmLog);
        }
        stmt.close();
        conn.close();
        System.out.println(list);
    }
    public void test() throws Exception {

    }
}
